package xml_tests.XMLParsing;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import xml_tests.BOOK.Employee;

public class SAXParserExample extends DefaultHandler {

    List<Employee> myEmpls;
    private String tempVal;
    // to maintain context
    private Employee tempEmp;
    private boolean isParsingErr;

    public SAXParserExample() {
        myEmpls = new ArrayList<Employee>();
        parseDocument();
        printData();
    }

    private void parseDocument() {
        // get a factory
        SAXParserFactory spf = SAXParserFactory.newInstance();
        try {
            // get a new instance of parser
            SAXParser sp = spf.newSAXParser();
            // parse the file and also register this class for call backs
            sp.parse("employees.xml", this);
        } catch (Exception ie) {
            System.out.println(ie.toString());
            isParsingErr = true;
        }
    }

    /**
     * Iterate through the list and print the contents
     */
    private void printData() {
        if (!isParsingErr) {
            System.out.println("No of Employees '" + myEmpls.size() + "'.");
            Iterator it = myEmpls.iterator();
            while (it.hasNext()) {
                System.out.println(it.next().toString());
            }
        }
    }

    // Event Handlers
    public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
        // reset
        tempVal = "";
        if (qName.equalsIgnoreCase("Employee")) {
            // create a new instance of employee
            tempEmp = new Employee();
            tempEmp.setType(attributes.getValue("type"));
        }
    }

    public void characters(char[] ch, int start, int length) throws SAXException {
        tempVal = new String(ch, start, length);
    }

    public void endElement(String uri, String localName, String qName) throws SAXException {
        if (qName.equalsIgnoreCase("Employee")) {
            // add it to the list
            myEmpls.add(tempEmp);
        } else if (qName.equalsIgnoreCase("Name")) {
            tempEmp.setName(tempVal);
        } else if (qName.equalsIgnoreCase("Id")) {
            tempEmp.setId(Integer.parseInt(tempVal));
        } else if (qName.equalsIgnoreCase("Age")) {
            tempEmp.setAge(Integer.parseInt(tempVal));
        }
    }

    public static void main(String[] args) {
        new SAXParserExample();
    }

}
